package com.baize.markwondemo.spans;

import android.graphics.Color;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;

import java.util.concurrent.atomic.AtomicBoolean;

public class ClickableSpanNoUnderline extends ClickableSpan {

  private static final String TAG = "ClickableSpan";

  private static final int NO_COLOR = -206;

  private static int MASK_COLOR = Color.BLACK;
//  private int color;

  private AtomicBoolean hideState = new AtomicBoolean(true);

  private OnClickListener onClickListener;

  public ClickableSpanNoUnderline(int color, OnClickListener onClickListener) {
    super();
    MASK_COLOR = color;
    this.onClickListener = onClickListener;
  }

  public ClickableSpanNoUnderline(OnClickListener onClickListener) {
    this(MASK_COLOR, onClickListener);
  }

  /**
   * Makes the text underlined and in the link color.
   *
   * @param ds
   */
  @Override
  public void updateDrawState(@NonNull TextPaint ds) {
//    super.updateDrawState(ds);
    Log.i("baize", "updateDrawState...");
    if (hideState.get()) {
      ds.setColor(MASK_COLOR);
      ds.bgColor = MASK_COLOR;    //背景色与前景色相同
    } else {
      ds.setColor(ds.getColor());
      ds.bgColor = Color.TRANSPARENT;
    }

    // 设置文字颜色
//        if (this.color == NO_COLOR) {
//            ds.setColor(ds.linkColor);
//        } else {
//            ds.setColor(this.color);
//        }
    ds.clearShadowLayer();
    // 去除下划线
    ds.setUnderlineText(false);
//        ds.bgColor = this.color;    //背景色与前景色相同
  }

  /**
   * Performs the click action associated with this span.
   *
   * @param widget widget
   */
  @Override
  public void onClick(View widget) {
    hideState.set(!hideState.get());
    widget.invalidate();
    if (this.onClickListener != null) {
      this.onClickListener.onClick(widget, this);
    } else {
      Log.w(TAG, "listener was null");
    }
  }

  /**
   * 回调接口，回调自身的onClick事件
   * 告诉外部 是否被点击
   */
  public interface OnClickListener<T extends ClickableSpanNoUnderline> {
    /**
     * ClickableSpan被点击
     *
     * @param widget widget
     * @param span   span
     */
    void onClick(View widget, T span);
  }

}
